#include"../source/server.hpp"
#include"../source/Socket.hpp"
#include<unordered_map>
std::unordered_map<uint64_t,PtrConnection> _conns;
uint64_t conn_id = 0;   
EventLoop baseloop;
std::vector<LoopThread> threads(2);
int next_loop = 0;
void ConnectionDestory(const PtrConnection &conn){
    _conns.erase(conn->Id());
    lg(Info,"Connection Destory:%p",conn.get());
    DBG_LOG("查看线程地址");
}

void OnConnected(const PtrConnection &conn){
    lg(Info,"Connection Established:%p",conn.get());
    DBG_LOG("查看线程地址");
}

void HandleEvent(const PtrConnection &conn){    
    std::cout<<"connId:"<<conn->Id()<<std::endl;
    DBG_LOG("查看线程地址");
}

void OnMessage(const PtrConnection &conn, Buffer *buf){
    lg(Info,"%s",buf->ReadPosition());
    buf -> MoveReadOffset(buf->ReadAbleSize());
    std::string str = "server hello World";
    conn->Send(str.c_str(),str.size());
    // conn->Shutdown();//调用关闭Connection
}

void NewConnnection(int fd){
    conn_id++;
    next_loop =(next_loop + 1) % 2;
    PtrConnection conn(new Connection(threads[next_loop].GetLoop(),conn_id,fd));
    conn->SetMessageCallback(OnMessage);    
    conn->SetConectedCallback(std::bind(OnConnected,std::placeholders::_1));
    conn->SetSvrConectedCallback(std::bind(ConnectionDestory,std::placeholders::_1));  
    conn->SetAnyEventCallback(std::bind(HandleEvent,std::placeholders::_1));  
    // conn->SetAnyEventCallback();   
    conn->EnabelInactiveRelease(5); //启动非活跃连接
    conn->Established(); //就绪序列化
    _conns.insert(std::make_pair(conn_id,conn));
    DBG_LOG("new ---------------");
}

int main(){ //先实现一个EventLoop,
    srand(time(NULL));
    Acceptor acceptor(&baseloop,8888);   //创建channel,并添加监控?在哪里添加监控？
    acceptor.SetAcceptCallback(std::bind(NewConnnection, std::placeholders::_1)); 
    // while(1){
    acceptor.Listen(); //开始监听
        baseloop.Start();//在这个里面一致循环，sleep(1)没有意义
    // }
    return 0;
}